<template>
    <div class="background">
        <div class="common-layout">
            <el-container>
                <el-header class="header_background">
                    <div style="position: absolute; top: 0.1%; left: 2%;">
                        <img alt="" src="@/assets/logo1.png" style="width: 40px;">
                    </div>
                    <div style="position: absolute; top: 1.5%; left: 38%;">
                        <span style="font-size: 15px; font-weight: bold; color: whitesmoke">
                          您好，用户&nbsp;&nbsp;{{ username }}&nbsp;&nbsp;！欢迎进入房屋租赁平台！
                        </span>
                    </div>
                    <div class="right-info">
                      <el-button @click="SignOut" style="margin-right: 10px;">
                        <el-icon :size="18" style="margin-right: 5px;">
                          <avatar />
                        </el-icon>
                        退出登录
                      </el-button>
                    </div>
                </el-header>
                <el-header class="sub_header_background">
                  <el-menu
                    :default-active="activeIndex"
                    router
                    class="el-menu-demo"
                    mode="horizontal"
                    background-color="#545c64"
                    text-color="whitesmoke"
                    active-text-color="white"
                    style="height: 102%;"
                    unique-opened
                  >
                    <el-menu-item index="/tenantHome">首页</el-menu-item>
                    <el-menu-item index="/TenantFavorite">我的收藏</el-menu-item>
                    <el-sub-menu index="transaction">
                      <template #title>交易管理</template>
                      <el-menu-item index="/TenantApplication">我的申请</el-menu-item>
                      <el-menu-item index="/TenantRecord">交易记录</el-menu-item>
                    </el-sub-menu>
                    <el-menu-item index="/SelectHouse">查看房源</el-menu-item>
                    <el-menu-item index="/VectorDatabase">向量数据库</el-menu-item>
                    <el-menu-item index="/PersonalAssistant">RAG问答助手</el-menu-item>
                    <el-menu-item index="/GraphRAGAssistant">GraphRAG问答助手</el-menu-item>
                    <el-menu-item index="/TenantSelfInfo">个人信息</el-menu-item>
                  </el-menu>
                </el-header>
                <el-main>
                    <el-card id="personal-info-card" style="margin: 5px; min-height: calc(100vh - 110px);">
                        <h1 style="text-align: center;">向量数据库</h1>
                        <h2 style="text-align: center;">帮助您一键获取最全房源信息</h2>
                        <div class="line" style="margin-left: 1.5%; margin-top: 1%;"></div>
                        <div style="display: flex; gap: 20px; margin: 20px 0; align-items: center;">
                            <h4 style="position: relative; left: 2%;">房源</h4>
                            <el-select 
                                v-model="selectedHouse" 
                                filterable 
                                remote 
                                reserve-keyword
                                placeholder="请输入房源名称" 
                                :remote-method="searchHouses"
                                :loading="loadingHouses"
                                style="position: relative; left: 1%; width: 25%;"
                                :filter-method="searchHouses"
                                @focus="loadAllHouses">
                                <el-option
                                    v-for="item in houseOptions"
                                    :key="item.title"
                                    :label="item.title"
                                    :value="item.title">
                                </el-option>
                            </el-select>
                            <h4 style="position: relative; left: 1%;">分块方式</h4>
                            <el-select 
                                v-model="chunkMethod" 
                                placeholder="请选择分块方式" 
                                style="position: relative; left: 0%; width: 25%;">
                                <el-option label="按大小分块" value="recursive"></el-option>
                                <el-option label="按语义分块" value="semantic"></el-option>
                            </el-select>
                            <h4 style="position: relative; left: 0%;">查看目标</h4>
                            <el-select 
                                v-model="checkMode" 
                                placeholder="请选择查看目标" 
                                style="position: relative; left: -1%; width: 25%;">
                                <el-option label="查看特定文档的分块内容" value="chunk"></el-option>
                                <el-option label="查看所有文档摘要" value="summary"></el-option>
                                <el-option label="查看数据库文件结构" value="structure"></el-option>
                            </el-select>
                        </div>
                        <div style="display: flex;">
                            <h3 style="position: relative; left: 2%;">向量数据库内容展示</h3>
                            <div class="line" style="margin-left: 4%;; margin-right: 4%; margin-top: 1%;"></div>
                            <!-- 保存按钮 -->
                            <el-button 
                                type="primary" 
                                icon="Download" 
                                circle 
                                @click="saveToFile"
                                :loading="saving"
                                title="保存"
                                style="position: relative; right: 0%">
                            </el-button>
                        </div>
                        <!-- 展示向量数据库中的内容 -->
                        <div style="margin: 20px; padding: 15px; border: 1px solid #ebeef5; border-radius: 4px; min-height: 300px;">
                          <pre v-if="summaryData">{{ summaryData }}</pre>
                          <pre v-else-if="structureData">{{ structureData }}</pre>
                          <pre v-else-if="chunkData">{{ chunkData }}</pre>
                          <div v-else style="color: #909399; text-align: center; line-height: 300px;">
                            请选择查看目标、房源名称与分块方式以获取数据
                          </div>
                        </div>
                    </el-card>
                </el-main>
            </el-container>
        </div>
    </div>
</template>
<script>
import request from "@/axios/request";
import request2 from "@/axios/request2";
import request3 from "@/axios/request3";
import request4 from "@/axios/request4";
import { ElMessage } from 'element-plus';

export default {
  data() {
    return {
      loading: true,
      loadingHouses: false,
      saving: false,
      tenantId: '',
      username: '',
      password: '',
      phone: '',
      email: '',
      selectedHouse: '',
      houseOptions: [],  
      allHouses: [],  
      chunkMethod: '',
      checkMode: '',
      chunkCheckTimer: null,
      summaryData: '',   
      structureData: '',   
      chunkData: ''
    };
  },
  mounted() {
    this.fetchUserInfo();
    this.loadAllHouses();
    this.loadVectorDatabase();
  },
  beforeUnmount() {
    if(this.chunkCheckTimer){
      clearInterval(this.chunkCheckTimer);
    }
  },
  methods: {
    async loadAllHouses() {
      this.loadingHouses = true;
      try {
        const res = await request.get("/house/findAll");
        if (res.code === 200) {
          this.allHouses = res.data || [];
          // 初始化时显示所有房源
          this.houseOptions = this.allHouses.map(item => ({
            houseId: item.houseId,
            title: item.title
          }));
        } else {
          ElMessage.error(res.msg || "加载房源数据失败");
        }
      } catch (err) {
        console.error("加载房源数据错误:", err);
        ElMessage.error("网络错误，请稍后再试");
      } finally {
        this.loadingHouses = false;
      }
    },

    async loadVectorDatabase() {
      this.$watch('checkMode', async (newVal) => {
        this.summaryData = '';
        this.structureData = '';
        this.chunkData = '';
        if (newVal === 'summary') {
          try {
            const res = await request3.get('/vector/summary');
            if (res.code === 200) {
              console.log('摘要数据:', res.data);
              this.summaryData = JSON.stringify(res.data, null, 2);
            } else {
              ElMessage.error(res.msg || "获取摘要数据失败");
            }
          } catch (err) {
            console.error("获取摘要数据错误:", err);
            ElMessage.error("网络错误，请稍后再试");
          }
        } else if (newVal === 'structure') {
          try {
            const res = await request3.get('/vector/structure');
            if (res.code === 200) {
              console.log('结构数据:', res.data);
              this.structureData = JSON.stringify(res.data, null, 2);
            } else {
              ElMessage.error(res.msg || "获取结构数据失败");
            }
          } catch (err) {
            console.error("获取结构数据错误:", err);
            ElMessage.error("网络错误，请稍后再试");
          }
        } else if (newVal === 'chunk') {
          this.checkChunkRequirements();
        }
      });

      this.$watch('selectedHouse', () => {
        if (this.checkMode === 'chunk') {
          this.checkChunkRequirements();
        }
      });

      this.$watch('chunkMethod', () => {
        if (this.checkMode === 'chunk') {
          this.checkChunkRequirements();
        }
      });
    },

    async checkChunkRequirements() {
      if (this.chunkCheckTimer) {
        clearInterval(this.chunkCheckTimer);
      }

      const checkAndLoad = async () => {
        if (!this.selectedHouse && this.checkMode === 'chunk') {
          ElMessage.warning("请选择房源");
          return false;
        }

        if (!this.chunkMethod && this.checkMode === 'chunk') {
          ElMessage.warning("请选择分块方式");
          return false;
        }

        try {
          const res = await request3.post('/vector/chunk', {
            params: {
              title: this.selectedHouse,
              chunkMethod: this.chunkMethod
            }
          });
          
          if (res.code === 200) {
            console.log('分块内容数据:', res.data);
            this.chunkData = JSON.stringify(res.data, null, 2);
            if (this.chunkCheckTimer) {
              clearInterval(this.chunkCheckTimer);
              this.chunkCheckTimer = null;
            }
            return true;
          } else {
            ElMessage.error(res.msg || "获取分块内容失败");
            return false;
          }
        } catch (err) {
          console.error("获取分块内容错误:", err);
          ElMessage.error("网络错误，请稍后再试");
          return false;
        }
      };

      const success = await checkAndLoad();
      
      if (!success) {
        this.chunkCheckTimer = setInterval(checkAndLoad, 10000);
      }
    },

    async fetchUserInfo() {
      let token = JSON.parse(window.sessionStorage.getItem('userInfo'));
      const tenantId = token.tenantId;
      const res = await request.get(`/tenant/findById/${tenantId}`);
      if (res.code === 200) {
        token=res.data;
      } else {
        ElMessage.error("获取用户信息失败");
      }
      console.log(token);
      if(!token) {
          ElMessage.error("获取用户信息失败");
          console.log("获取用户信息失败");
          return;
      }
      this.tenantId = token.tenantId;
      this.username = token.username;
      this.password = token.password;
      this.phone = token.phone;
      this.email = token.email;

      console.log(token);
    },
    // 搜索房源
    searchHouses(query) {
      if (!query) {
        this.houseOptions = this.allHouses.map(item => ({
          houseId: item.houseId,
          title: item.title
        }));
        return;
      }
      
      const filteredHouses = this.allHouses.filter(item => 
        (item.title).toLowerCase().includes(query.toLowerCase())
      );
      
      this.houseOptions = filteredHouses.map(item => ({
        houseId: item.houseId,
        title: item.title
      }));
    },
    // 保存到文件
    async saveToFile() {
      if (!this.selectedHouse && this.checkMode === 'chunk') {
        ElMessage.warning("请选择房源");
        return;
      }
      
      if (!this.chunkMethod && this.checkMode === 'chunk') {
        ElMessage.warning("请选择分块方式");
        return;
      }

      if (!this.checkMode) {
        ElMessage.warning("请选择查看目标");
        return;
      }
      
      this.saving = true;
      try {
        const res = await request4.post('/vector/save', {
          title: this.selectedHouse,
          chunkMethod: this.chunkMethod,
          checkMode: this.checkMode
        });
        
        if (res.code === 200) {
          ElMessage.success("文件保存成功 (保存路径：D:\\\\Edge下载)");
        } else {
          ElMessage.error(res.msg || "保存失败");
        }
      } catch (err) {
        console.error("保存文件错误:", err);
        ElMessage.error("网络错误，请稍后再试");
      } finally {
        this.saving = false;
      }
    },
    SignOut() {
      sessionStorage.clear();
      ElMessage({
          message: '用户退出登录',
          type: 'success',
      });
      this.$router.replace({ path: '/Login' });
    },
  }
};
</script>

<style scoped>
.background {
  background-color: whitesmoke;
  height: 100vh;
}
.header_background {
  background-color: #1b4989;
  height: 6vh;
}
.sub_header_background {
  background-color: #545c64;
  height: 7vh;
}
.right-info {
  width: 100px;
  position: absolute;
  right: 2%;
  top: 0.7%
}

.right-info:hover {
  cursor: pointer;
}
.el-carousel__item h3 {
  color: #475669;
  opacity: 0.75;
  line-height: 200px;
  margin: 0;
  text-align: center;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}

.el-card:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 15px rgba(0, 0, 0, 0.2), 0 6px 20px rgba(0, 0, 0, 0.2);
  border-color: #409EFF;
}

.line{ 
  background: url(https://www.upc.edu.cn/ximages/tit1.png) center repeat-x; 
  height: 0.4rem; 
  flex: 1; 
  background-size: auto;
  margin: 0.16rem;
}
</style>